<?php

namespace App\GraphQL\Mutations\Order;

use App\Jobs\EnableWechatJob;
use App\Models\Device;
use App\Models\MarketingPolicy;
use App\Models\Order;
use App\Models\PriceSpecification;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class Create
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        
        $data = $args['input'];
        $device = $this->validate($data);
        $priceSpecification = PriceSpecification::find($data['price_specification_id']);
        $channel = request()->header('mode','wechats') === 'wechats' ? 'WECHAT' : 'ALIPAY';
        $paidPrice = $priceSpecification->price;
        $marketingPolicyID = $data['marketing_policy_id']?:0;
        $marketingPolicyRuleID = 0;
        $orderData = [
            'device_id'=>$data['device_id'],
            'device_group_id'=>$device->device_group_id,
            'device_style'=>$device->device_style,
            'channel'=>$channel,
            'member_id'=>auth()->user()->id,
            'time_length'=>$priceSpecification->duration,
            'price'=>$priceSpecification->price,
            'price_specification_id'=>$priceSpecification->id,
            'price_specification_name'=>$priceSpecification->name,
            'business_name'=>'成都卓见未来信息科技',
            'status'=>'WAIT_PAY',
            'paid_price'=>$paidPrice,
            'marketing_policy_id'=>$marketingPolicyID,
            'marketing_policy_rule_id'=>$marketingPolicyRuleID,
            'platform_open_id'=>auth()->user()->open_id
        ];
        if($data['marketing_policy_id']){
            $marketingPolicy = MarketingPolicy::find($data['marketing_policy_id']);
            if(!$marketingPolicy){
                throw new \Exception('策略不存在!');
            }
            if($marketingPolicy->cate==='FREE'){
                $orderData['paid_price'] = 0;
            } else {
                $marketingPolicyRule = $marketingPolicy->main_rule;
                if ($marketingPolicyRule) {
                    $marketingPolicyRuleID = $marketingPolicyRule->id;
                    switch ($marketingPolicyRule->cate){
                        case 'ALLOWANCE':
                            $paidPrice = $paidPrice * ($marketingPolicyRule->preference/10000);
                            $orderData['paid_price'] = $paidPrice>=0?:0;
                            break;
                        case 'DERATE':
                            $paidPrice = $paidPrice - $marketingPolicyRule->preference;
                            $orderData['paid_price'] = $paidPrice>=0?:0;
                            break;
                        default:
                            break;
                    }
                }else {
                    throw new \Exception('策略规则不存在!');
                }
            }
        }
        if($orderData['paid_price'] === 0){
            $orderData['status'] = 'PAY_SUCCESS';
            $orderData['pay_time'] = Carbon::now();
        }
        // 判断账户当日未支$channelchannel')
        $startTime = Carbon::now()->startOfDay();
        $endTime = Carbon::now()->endOfDay();
        $count = Order::where('channel',$channel)->where('status','WAIT_PAY')->whereBetween('created_at',[$startTime,$endTime])->count();
        if($count>=9){
            $authUser = auth()->user();
            $authUser->status = 'DISABLE';
            $authUser->disable_time = Carbon::now()->addDays(7);
            $authUser->save();
            if($channel==='WECHAT'){
                EnableWechatJob::dispatch($authUser)->delay(Carbon::now()->addDays(7));
            }
            throw new \Exception('账户被冻结,将在'.$authUser->disable_time.'解冻');
        }
        $order = Order::create($orderData);
        return $order;
    }
    public function validate($data){
        $authUser = auth()->user();
        if ($authUser->status === 'DISABLE'){
            throw new \Exception('账户被冻结,将在'.$authUser->disable_time.'解冻');
        }
        $rules = [
            'price_specification_id'=>['required'],
            'device_id'=>['required'],
        ];
        $messages = [
            'price_specification_id.required'=>'价格不能为空',
            'device_id.required'=>'设备不能为空',
        ];
        $validate = Validator::make($data,$rules,$messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        // 验证用户是否存在
        $price = PriceSpecification::find($data['price_specification_id']);
        if (!$price) {
            throw new \Exception('价格不存在!');
        }
        $device = Device::find($data['device_id']);
        if (!$device) {
            throw new \Exception('设备不存在!');
        }
        return $device;
    }
}
